package com.cx.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.HashMap;

/**
 * @auther: Centaury
 * @Date:2023/3/22 - 03 - 22 - 15:12
 */
@Configuration
public class DruidConfig {

    // 将配置文件与yaml绑定
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }

    /**
     * 后台监控 (代码为固定格式) 相当于web.xml
     * springboot内置了servlet容器 ,所有没有web.xml ,
     * 将替代方法注册进 Bean, 想注册什么就 new什么
     *  注意点: new StatViewServlet(), "/druid/*" 中的映射写* , **无法进入后台监控页面
     *  @return ServletRegistrationBean
     */
    @Bean
    public ServletRegistrationBean StatViewServlet(){
        // 获取监控
        ServletRegistrationBean<StatViewServlet> bean =
                new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        // 后台需要有人登录 ,账号密码配置
        HashMap<String,String> initParameters = new HashMap<>();
        // 增加配置
        initParameters.put("loginUsername","admin"); // 登录key是固定的 loginUsername loginPassword
        initParameters.put("loginPassword","123456");
        initParameters.put("allow",""); // 允许谁能访问, ""表示任何人都可以访问
        // initParameters.put("用户名","IP地址"); // 禁止访问IP

        bean.setInitParameters(initParameters); // 设置初始化参数
        return bean;
    }

    // filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());

        // 需要过滤的请求
        HashMap<String,String> initParameters = new HashMap<>();
        // 这些请求不进行统计
        initParameters.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParameters);

        return bean;
    }
}
